<template>
  <div style="margin-top: 20px">
    <el-row>
      <el-button @click="addForm">
        添加
      </el-button>
      <span style="float: right">拖拽调整顺序</span>
    </el-row>
    <el-row>
      <el-col :span="23">
        <el-table-draggable>
          <el-table
            :data="form.ReportForms"
            :height="tableHeight"
            border
            fit
            highlight-current-row
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column label="名称" prop="Name" />
            <el-table-column label="类型">
              <template slot-scope="scope">
                {{ scope.row.Type | dictFilter(enums.reportFormTypeEnum) }}
              </template>
            </el-table-column>
            <el-table-column label="属性" prop="AttributeName" />
            <el-table-column label="字典" prop="DictCategoryName" />
            <el-table-column label="是否返回字典">
              <template slot-scope="scope">
                {{ scope.row.ReturnAllDict | booleanFilter }}
              </template>
            </el-table-column>
            <el-table-column label="报表" prop="QueryReportCode" />

            <el-table-column label="是否必填">
              <template slot-scope="scope">
                {{ scope.row.Required | booleanFilter }}
              </template>
            </el-table-column>
            <el-table-column label="默认值" prop="DefaultValue" />
            <el-table-column>
              <template slot-scope="scope">
                <el-button type="text" @click="editForm(scope.row)">
                  修改
                </el-button>
                <el-button type="text" @click="removeForm(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-table-draggable>
        <el-row style="margin-top: 15px">
          <el-button type="primary" @click="save">
            保存
          </el-button>
          <el-button @click="close">
            取消
          </el-button>
        </el-row>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="editFormDialog.show" :close-on-click-modal="false">
      <el-form ref="editFormDialog" :model="editFormDialog" label-width="150px">
        <el-form-item label="名称" prop="Name" :rules="[{required: true, message: '请输入'}]">
          <el-input v-model="editFormDialog.Name" />
        </el-form-item>
        <el-form-item label="属性" prop="AttributeName" :rules="[{required: true, message: '请输入'}]">
          <el-input v-model="editFormDialog.AttributeName" />
        </el-form-item>
        <el-form-item label="类型" prop="Type" :rules="[{required: true, message: '请输入'}]">
          <el-select v-model="editFormDialog.Type" style="width: 99%" @change="typeChange">
            <el-option
              v-for="item in enums.reportFormTypeEnum"
              :key="item.value"
              :label="item.text"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否必填" prop="Required">
          <el-switch v-model="editFormDialog.Required" />
        </el-form-item>
        <el-form-item label="默认值" prop="DefaultValue">
          <el-autocomplete
            v-model="editFormDialog.DefaultValue"
            style="width: 99%"
            :fetch-suggestions="defaultValueSuggest"
          >
            <template slot-scope="{ item }">
              <el-tooltip effect="light" :content="item.label" :hide-after="1000" placement="top-end">
                <div>
                  <div class="name">
                    {{ item.value }}
                  </div>
                  <span class="label">{{ item.label }}</span>
                </div>
              </el-tooltip>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item v-show="editFormDialog.Type === enums.reportFormTypeEnum.SELECT.value || editFormDialog.Type === enums.reportFormTypeEnum.MULTI_SELECT.value" label="是否返回字典" prop="IsShow">
          <el-switch v-model="editFormDialog.ReturnAllDict" />
        </el-form-item>
        <el-form-item v-show="editFormDialog.Type === enums.reportFormTypeEnum.SELECT.value || editFormDialog.Type === enums.reportFormTypeEnum.MULTI_SELECT.value" label="字典类型" prop="DictCategoryId">
          <el-select v-model="editFormDialog.DictCategoryId" placeholder="请选择" filterable clearable style="width: 99%" @change="dictChange">
            <el-option
              v-for="item in dictCategoryList"
              :key="item.DictionaryCategoryId"
              :label="item.CategoryName"
              :value="item.DictionaryCategoryId"
            >
              <span style="float: left">{{ item.CategoryName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.CategoryCode }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="editFormDialog.Type === enums.reportFormTypeEnum.REPORT.value" label="报表" prop="QueryReportCode">
          <el-select v-model="editFormDialog.QueryReportCode" placeholder="请选择" filterable clearable style="width: 99%">
            <el-option
              v-for="item in reportList"
              :key="item.ReportId"
              :value="item.Code"
              :label="item.Name+'('+item.Code+')'"
            >
              <span style="float: left">{{ item.Name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.Code }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="额外配置" prop="ExtraConfig">
          <el-input v-model="editFormDialog.ExtraConfig" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveForm">
              保存
            </el-button>
            <el-button @click="editFormDialog.show = false">
              取消
            </el-button>
          </el-form-item>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import reportApi from '@/api/report'
import commonValidator from '@/utils/commonValidator'
import reportFormTypeEnum from '@/enums/report/reportFormTypeEnum'
import apolloClient from '@/utils/graphql'
import gql from 'graphql-tag'
import ElTableDraggable from 'element-ui-el-table-draggable'
import reportTypeEnum from '@/enums/report/reportTypeEnum'
import displayTypeEnum from '@/enums/report/displayTypeEnum'

export default {
  name: 'ReportFormInfo',
  components: {
    ElTableDraggable
  },
  props: {
    // id
    id: {
      type: String,
      required: false
    }
  },
  data() {
    return {
      // 表单数据
      form: {
        ReportDbId: this.id,
        ReportForms: []
      },
      enums: {
        reportFormTypeEnum
      },
      editFormDialog: {
        show: false,
        Name: null,
        AttributeName: null,
        item: null,
        Type: null,
        DictCategoryId: null,
        ReturnAllDict: true,
        ExtraConfig: null,
        DefaultValue: null,
        Required: false,
        QueryReportCode: null
      },
      commonValidator,
      dictCategoryList: [],
      dictList: [],
      reportList: []
    }
  },
  computed: {
    tableHeight() {
      return document.body.clientHeight - 300
    }
  },
  mounted() {
    this.getDetail()
    this.getDictCategoryList()
    this.getReportList()
  },
  methods: {
    getReportList() {
      var postData = {}
      postData.Type = reportTypeEnum.SQL.value
      postData.DisplayType = [displayTypeEnum.LIST.value, displayTypeEnum.PAGE.value]
      apolloClient.query({
        fetchPolicy: 'network-only',
        query: gql`query getReportList($Req: ReportListReq!){
                    reportList(Req: $Req){
                        ReportId
                        Code
                        Name
                    }
                 }`,
        variables: { Req: postData }
      }).then(response => {
        if (response.data) {
          this.reportList = response.data.reportList
        }
      })
    },
    dictChange() {
      console.log('dict change')
      if (this.editFormDialog.DictCategoryId) {
        this.getDictValueList(this.editFormDialog.DictCategoryId)
      } else {
        this.dictList = []
      }
    },
    up(i) {
      var t = this.form.ReportForms.splice(i, 1)
      this.form.ReportForms.splice(i - 1, 0, t[0])
    },
    down(i) {
      var t = this.form.ReportForms.splice(i, 1)
      this.form.ReportForms.splice(i + 1, 0, t[0])
    },
    // 获取字典类型列表
    getDictCategoryList() {
      apolloClient.query({
        fetchPolicy: 'network-only',
        query: gql`query {
                    dictCategoryList{
                        DictionaryCategoryId
                        CategoryName
                        CategoryCode
                    }
                 }`,
        variables: {}
      }).then(response => {
        if (response.data) {
          this.dictCategoryList = response.data.dictCategoryList
        }
      })
    },
    getDictValueList(categoryId) {
      apolloClient.query({
        fetchPolicy: 'network-only',
        query: gql`query dictList($data:String!){
                    dictList(dictCategoryId: $data){
                        Records{
                            Value
                            Name
                            Remarks
                        }
                    }
                 }`,
        variables: { data: categoryId }
      }).then(response => {
        if (response.data && response.data.dictList) {
          this.dictList = response.data.dictList.Records || []
        }
      })
    },
    saveForm() {
      this.$refs.editFormDialog.validate((valid) => {
        if (valid) {
          if (this.editFormDialog.item) {
            this.editFormDialog.item.Type = this.editFormDialog.Type
            this.editFormDialog.item.Name = this.editFormDialog.Name
            this.editFormDialog.item.AttributeName = this.editFormDialog.AttributeName
            this.editFormDialog.item.ExtraConfig = this.editFormDialog.ExtraConfig
            this.editFormDialog.item.DictCategoryId = this.editFormDialog.DictCategoryId
            this.editFormDialog.item.ReturnAllDict = this.editFormDialog.ReturnAllDict
            this.editFormDialog.item.DefaultValue = this.editFormDialog.DefaultValue
            this.editFormDialog.item.Required = this.editFormDialog.Required
            this.editFormDialog.item.QueryReportCode = this.editFormDialog.QueryReportCode
            this.editFormDialog.item.DictCategoryName = this.getCategoryNameById(this.editFormDialog.item.DictCategoryId)
          } else {
            var item = {}
            item.Type = this.editFormDialog.Type
            item.Name = this.editFormDialog.Name
            item.AttributeName = this.editFormDialog.AttributeName
            item.ExtraConfig = this.editFormDialog.ExtraConfig
            item.DictCategoryId = this.editFormDialog.DictCategoryId
            item.ReturnAllDict = this.editFormDialog.ReturnAllDict
            item.DefaultValue = this.editFormDialog.DefaultValue
            item.Required = this.editFormDialog.Required
            item.QueryReportCode = this.editFormDialog.QueryReportCode
            item.DictCategoryName = this.getCategoryNameById(item.DictCategoryId)
            this.form.ReportForms.push(item)
          }
          this.editFormDialog.show = false
        }
      })
    },
    getCategoryNameById(dictCategoryId) {
      for (const dictCategory of this.dictCategoryList) {
        if (dictCategoryId === dictCategory.DictionaryCategoryId) {
          return dictCategory.CategoryName
        }
      }
      return ''
    },
    typeChange() {
      this.editFormDialog.DefaultValue = null
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.PROVINCE.value) {
        this.editFormDialog.AttributeName = 'province_id'
      }
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.CITY.value) {
        this.editFormDialog.AttributeName = 'city_id'
      }
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.DISTRICT.value) {
        this.editFormDialog.AttributeName = 'district_id'
      }
    },
    defaultValueSuggest(queryString, cb) {
      console.log('default value suggest')
      if (!this.editFormDialog.Type) {
        cb([])
        return
      }
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.TEXT.value) {
        cb([{ value: '""', label: '空字符串' }])
        return
      }
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.NUMBER.value) {
        cb([{ value: '0', label: '0值' }])
        return
      }
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.DATETIME.value) {
        cb([{ value: 'ctx.now', label: '当前时间' }, { value: 'ctx.miment.add(-1, "DD")', label: '昨天' }])
        return
      }
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.SELECT.value) {
        var ss = []
        if (this.dictList) {
          for (const dictListElement of this.dictList) {
            ss.push({ value: dictListElement.Value + '', label: dictListElement.Remarks })
          }
        } else {
          ss.push({ value: '1', label: '例子:字典的value' })
        }
        ss.push({ value: 'ctx.provinceId', label: '当前省份' })
        ss.push({ value: 'ctx.cityId', label: '当前城市' })
        ss.push({ value: 'ctx.districtId', label: '当前区县' })
        cb(ss)
        return
      }
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.HIDDEN.value) {
        cb([])
        return
      }
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.DATE.value) {
        cb([{ value: 'ctx.now', label: '当前时间' }, { value: 'ctx.miment.add(-1, "DD")', label: '昨天' }])
        return
      }
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.TIME.value) {
        cb([{ value: 'ctx.now', label: '当前时间' }, { value: 'ctx.miment.add(-1, "DD")', label: '昨天' }])
        return
      }
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.MULTI_SELECT.value) {
        cb([])
        return
      }
      if (this.editFormDialog.Type === this.enums.reportFormTypeEnum.PROVINCE_CITY_AREA.value) {
        cb([])
        return
      }
      cb([])
      /* var results = queryString ? cityArray.filter(this.cityFilter(queryString)) : cityArray
      cb(results)*/
    },
    addForm() {
      this.editFormDialog.Type = null
      this.editFormDialog.AttributeName = null
      this.editFormDialog.Name = null
      this.editFormDialog.item = null
      this.editFormDialog.DictCategoryId = null
      this.editFormDialog.ExtraConfig = null
      this.editFormDialog.DefaultValue = null
      this.editFormDialog.ReturnAllDict = true
      this.editFormDialog.Required = false
      this.editFormDialog.QueryReportCode = null

      this.dictChange()
      this.editFormDialog.show = true
    },
    editForm(row) {
      this.editFormDialog.Type = row.Type
      this.editFormDialog.AttributeName = row.AttributeName
      this.editFormDialog.Name = row.Name
      this.editFormDialog.DictCategoryId = row.DictCategoryId
      this.editFormDialog.ExtraConfig = row.ExtraConfig
      this.editFormDialog.ReturnAllDict = row.ReturnAllDict
      this.editFormDialog.DefaultValue = row.DefaultValue
      this.editFormDialog.Required = row.Required
      this.editFormDialog.item = row
      this.editFormDialog.QueryReportCode = row.QueryReportCode

      this.dictChange()
      this.editFormDialog.show = true
    },
    removeForm(index) {
      this.form.ReportForms.splice(index, 1)
    },
    getDetail() {
      console.log('get detail')
      reportApi.getReportFormList(this.id).then(response => {
        if (response.data) {
          this.form = response.data.reportDetail
        } else {
          this.$notify.error(response.errors[0].message)
        }
      }).catch((err) => {
        this.$notify.error(err.message)
      })
    },
    // 保存数据
    save() {
      var postData = {}
      postData.ReportId = this.form.ReportId
      postData.FormItems = []
      for (const reportForm of this.form.ReportForms) {
        var item = {}
        item.Name = reportForm.Name
        item.AttributeName = reportForm.AttributeName
        item.Type = reportForm.Type
        item.DictCategoryId = reportForm.DictCategoryId
        item.ReturnAllDict = reportForm.ReturnAllDict
        item.ExtraConfig = reportForm.ExtraConfig
        item.Required = reportForm.Required
        item.DefaultValue = reportForm.DefaultValue
        item.QueryReportCode = reportForm.QueryReportCode
        postData.FormItems.push(item)
      }
      reportApi.updateReportForm(postData).then(response => {
        console.log(response)
        if (response.data.updateReportForm) {
          this.$notify.success('保存成功')
          this.close()
        } else {
          this.$notify.error(response.errors[0].message)
        }
      }).catch((err) => {
        this.$notify.error(err.message)
      })
    },
    close() {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.el-autocomplete-suggestion {
        li {
            .label {
                font-size: 12px;
                color: #b4b4b4;
            }

        }

}

</style>
